package com.dmlll.utils;

import org.apache.commons.io.FileUtils;
import org.apache.xmlbeans.impl.util.Base64;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Properties;


public class Upload {
    /**
     * 文件上传路径
     */
    public static String PATH = "D:\\";
    static {
        InputStream stream = Upload.class.getClassLoader().getResourceAsStream("path.properties");
        Properties properties = new Properties();
        try {
            properties.load(stream);
            PATH = properties.getProperty("path");
            System.out.println(PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void downloadFile(HttpServletResponse response, String path, String oldName) {
        //使用绝对路径+相对路径去找到文件路径
        File file = new File(path);
        //判断文件是否存在
        if (file.exists()&&file.isFile()) {
            try {
                //如果名字有中文的要处理编码
                try {
                    oldName = URLEncoder.encode(oldName, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //把file转成转成bytes
                byte[] bytes = FileUtils.readFileToByteArray(file);
                String metaType = "data:image/jpeg;base64,";
                InputStream inputStream = new FileInputStream(file);
                ServletOutputStream servletOutputStream = response.getOutputStream();
                inputStream.read(bytes);
                servletOutputStream.write(metaType.getBytes());
                servletOutputStream.write(Base64.encode(bytes));
                inputStream.close();
                servletOutputStream.flush();
                servletOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            PrintWriter out;
            try {
                out = response.getWriter();
                out.write("文字不存在");
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
